import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { message } from 'antd';
import React, { useRef, useState } from 'react';
import EditForm from './components/EditForm';
import type { ResponseData } from '@/utils/request';
import { SystemConfigItem } from './types';
import { editSystemConfig, pageQuerySystemConfig } from './service';
import RemoteSelect from '@/components/RemoteSelect';
import { getTenantList } from '@/pages/Tenant/Tenant/service';
import { useModel } from 'umi';

const TableList: React.FC<{}> = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const { 'CONFIG.UPDATE': update, 'CONFIG.GET': get } = currUser;

  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [systemConfigData, setSystemConfigData] = useState<SystemConfigItem>({
    id: '',
    tenant_id: '',
  });
  const actionRef = useRef<ActionType>();

  async function handleEdit(fields: SystemConfigItem) {
    const hide = message.loading('正在修改');
    try {
      const response: ResponseData<SystemConfigItem> = await editSystemConfig(fields);
      hide();
      if (response.code === 0) {
        message.success('修改成功');
        actionRef.current?.reload();
        handleEditModalVisible(false);
      } else {
        message.error(response.message);
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
    }
  }

  const columns: ProColumns<SystemConfigItem>[] = [
    {
      title: '租户',
      dataIndex: 'tenant_id',
      onFilter: true,
      render: (_, record) => {
        return record.tenant_name;
      },
      renderFormItem: () => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'name' }}
          request={() => getTenantList({})}
        />
      ),
    },
    {
      title: '置信度',
      dataIndex: 'believe_degree',
      search: false,
    },
    {
      title: '失败重推',
      dataIndex: 'fail_repush',
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onClickEdit = () => {
          handleEditModalVisible(true);
          setSystemConfigData(record);
        };
        return <div>{update && <a onClick={onClickEdit}>编辑</a>}</div>;
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<SystemConfigItem>
        headerTitle="系统参数"
        actionRef={actionRef}
        rowKey="id"
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        scroll={{ x: true }}
        tableAlertRender={() => false}
        request={async (params) => {
          params.tenant_id = params.tenant_id?.id;
          const res = pageQuerySystemConfig(params);
          return res;
        }}
        columns={columns}
        rowSelection={false}
      />

      {editModalVisible && systemConfigData && (
        <EditForm
          config={systemConfigData}
          modalVisible={editModalVisible}
          onSubmit={handleEdit}
          onCancel={() => handleEditModalVisible(false)}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
